package com.yc.web.servlets;

import com.yc.bean.Cust;
import com.yc.model.JsonModel;
import com.yc.utils.EncryptUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author zwei
 * @create 2024-05-17 20:02
 */
@WebServlet("/cust.action")
public class CustServlet extends BaseServlet{
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session=req.getSession();
        JsonModel jm=new JsonModel();
        session.removeAttribute("logincust");
        jm.setCode(1);
        super.writeJson(jm,resp);
    }

    protected void getLoginStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JsonModel jm=new JsonModel();
        //取出session中的验证码
        HttpSession session=req.getSession();

        if (session.getAttribute("logincust")==null){
            jm.setCode(0);
        }else {
            jm.setCode(1);
            jm.setObj(session.getAttribute("logincust"));
        }
        super.writeJson(jm,resp);
    }
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchAlgorithmException {
        JsonModel jm = new JsonModel();
        //取出session中的验证码
        HttpSession session = req.getSession();
        Cust c=super.parseObjectFromRequest(req,Cust.class);
        String valcode=req.getParameter("valcode");
        //取验证码
        String code= (String) session.getAttribute("code");
        if (!code.equals(valcode)){
            jm.setCode(0);
            jm.setError("验证码错误。。。");
            super.writeJson(jm,resp);
            return;
        }
        String newPwd= EncryptUtils.encryptToMD5(EncryptUtils.encryptToMD5(c.getPwd()));
        c.setPwd(newPwd);

        String sql="select*from cust where name=? and pwd=?";
        List<Cust>list=dbHelper.select(Cust.class,sql,c.getName(),c.getPwd());
        if (list!=null&&list.size()>0){
            session.setAttribute("logincust",list.get(0));
            jm.setCode(1);
            jm.setObj(list.get(0));
        }else {
            jm.setCode(0);
            jm.setError("用户名或密码错误！");
        }
        super.writeJson(jm,resp);
    }
}
